/*
 *
 *  *    Copyright 2020-2021 Luter.me
 *  *
 *  *    Licensed under the Apache License, Version 2.0 (the "License");
 *  *    you may not use this file except in compliance with the License.
 *  *    You may obtain a copy of the License at
 *  *
 *  *      http://www.apache.org/licenses/LICENSE-2.0
 *  *
 *  *    Unless required by applicable law or agreed to in writing, software
 *  *    distributed under the License is distributed on an "AS IS" BASIS,
 *  *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  *    See the License for the specific language governing permissions and
 *  *    limitations under the License.
 *
 */

package com.demo.controller;

import com.luter.heimdall.core.authorization.provider.DocumentUsersDataProvider;
import com.luter.heimdall.core.authorization.provider.model.UserDO;
import com.luter.heimdall.core.details.UserDetails;
import com.luter.heimdall.core.exception.HeimdallException;
import com.luter.heimdall.core.manager.AuthorizationManager;
import com.luter.heimdall.core.token.SimpleToken;
import com.luter.heimdall.core.utils.ObjUtil;
import com.luter.heimdall.core.utils.crypto.Md5Util;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
public class UserController {

    private final AuthorizationManager authorizationManager;

    /**
     * 登录
     */
    @GetMapping("/login")
    public String login(String username, String password) {
        //从配置文件加载用户信息
        final UserDO userVO = DocumentUsersDataProvider.loadUserByUserName(username);
        //没这个用户
        if (null == userVO) {
            throw new HeimdallException("用户名或者密码错误");
        }
        //对比一下跟配置文件中 Md5 密码是否一致
        if (!Md5Util.matches(password, userVO.getPassword())) {
            throw new HeimdallException("用户名或者密码错误");
        }
        //构造 UserDetails，执行登录。
        return authorizationManager.getAuthenticationManager()
                .login(new UserDetails().setAppId(userVO.getAppId())
                        .setUserId(userVO.getUserId())
                        //把用户信息放在附加字段里
                        .setAttributes(ObjUtil.ConvertObjectToMap(userVO, "password", "perms")));
    }

    /**
     * 获取当前登录用户Token
     */
    @GetMapping("/current")
    public SimpleToken current() {
        return authorizationManager.getAuthenticationManager().getCurrentToken(true);
    }
}
